#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

#define MAX_CLIENTS 10
#define MAX_BUFFER_SIZE 1024

static int client_sockets[MAX_CLIENTS]; // 存储客户端socket描述符的数组
static int num_clients = 0;             // 当前连接的客户端数量

void *handle_client(void *socket_desc)
{
    int client_sock = *(int *)socket_desc;
    char buffer[MAX_BUFFER_SIZE];
    int nbytes;

    while ((nbytes = read(client_sock, buffer, sizeof(buffer))) > 0)
    {
        buffer[nbytes] = '\0';
        printf("%s\n", buffer); // 打印客户端发送的消息

        // 将消息发送给所有其他客户端
        for (int i = 0; i < num_clients; i++)
        {
            if (client_sockets[i] != client_sock)
            {
                write(client_sockets[i], buffer, strlen(buffer));
            }
        }

        // 如果客户端发送了"Quit"消息，则断开连接
        if (strcmp(buffer, "Quit") == 0)
        {
            break;
        }
    }

    // 关闭客户端socket连接
    close(client_sock);

    // 从数组中移除该客户端socket
    for (int i = 0; i < num_clients; i++)
    {
        if (client_sockets[i] == client_sock)
        {
            for (int j = i; j < num_clients - 1; j++)
            {
                client_sockets[j] = client_sockets[j + 1];
            }
            num_clients--;
            break;
        }
    }

    free(socket_desc);
    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    int sockfd, client_sock;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);
    pthread_t thread_id;

    // 创建socket
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        fprintf(stderr, "SocketError:%s\n", strerror(errno));
        exit(1);
    }

    // 绑定地址和端口
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[1]));
    server_addr.sin_addr.s_addr = INADDR_ANY;
    if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        fprintf(stderr, "BindError:%s\n", strerror(errno));
        exit(1);
    }

    // 监听连接
    if (listen(sockfd, MAX_CLIENTS) == -1)
    {
        fprintf(stderr, "ListenError:%s\n", strerror(errno));
        exit(1);
    }

    printf("服务器已启动，监听端口：%s\n", argv[1]);

    while (1)
    {
        // 接受客户端连接
        if ((client_sock = accept(sockfd, (struct sockaddr *)&client_addr, &client_len)) == -1)
        {
            fprintf(stderr, "AcceptError:%s\n", strerror(errno));
            continue;
        }

        // 将客户端socket添加到数组中
        client_sockets[num_clients++] = client_sock;

        // 创建一个线程来处理该客户端连接
        int *new_sock = malloc(sizeof(int));
        *new_sock = client_sock;
        if (pthread_create(&thread_id, NULL, handle_client, (void *)new_sock) < 0)
        {
            fprintf(stderr, "ThreadError:%s\n", strerror(errno));
            exit(1);
        }

        // 分离线程，使得线程结束后自动释放资源
        pthread_detach(thread_id);
    }

    // 关闭socket
    close(sockfd);

    return 0;
}

